package crawler.proxy.uitl;

import crawler.douban.DouBanSpider;
import crawler.proxy.Proxy;
import crawler.proxy.impl.*;

import java.util.*;
import java.util.concurrent.*;

/**
 * USER: lintc 【lintiancong@zhuojianchina.com】
 * DATE: 2017-09-11 11:16
 */
public class ProxyList {

    // 可用线程列表
    public static Queue<Proxy> proxyIpList = new ConcurrentLinkedQueue<>();

    // 代理爬虫列表
    private static List<ProxyUtil> proxyCatchList = new ArrayList<>();

    static {
        proxyCatchList.add(new ProxyUtil(new JiSuProxy(), null));
        proxyCatchList.add(new ProxyUtil(new OneEightOneProxy(), null));
        proxyCatchList.add(new ProxyUtil(new SixSixProxy(), null));
        proxyCatchList.add(new ProxyUtil(new XiciProxy(), null));
        proxyCatchList.add(new ProxyUtil(new NiansProxy(), null));
        proxyCatchList.add(new ProxyUtil(new ThreeThreeSixSixProxy(), null));
    }

    /**
     * 保存代理 线程安全
     * @param proxy
     */
    public static void setProxy(Proxy proxy) {
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (proxyIpList) {
            if (!proxyIpList.contains(proxy)) {
                proxyIpList.add(proxy);
            }
        }
    }

    /**
     * 获取代理
     * @return
     */
    public static Proxy getProxy() {
        Proxy proxy = ProxyList.proxyIpList.poll();
        while (null == proxy) {
            proxy = ProxyList.proxyIpList.poll();
            DouBanSpider.friendlyToDouban(1);
        }
        return proxy;
    }

    /**
     * 初始化代理池抓取
     */
    public static void initialization() {
        for (ProxyUtil proxyUtil : proxyCatchList) {
            new Thread(proxyUtil).start();
        }
    }

    /**
     * 代理抓取关闭
     */
    public static void proxyStop() {
        for (ProxyUtil proxyUtil : proxyCatchList) {
            proxyUtil.stop();
        }
    }

    public static void main(String[] args) {

    }

}
